import React, { Suspense } from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import reportWebVitals from './reportWebVitals'
// BrowserRouter 为 history 模式; HashRouter 为 hash 模式
import {
    Navigate,
    Route,
    BrowserRouter as Router,
    Routes,
} from 'react-router-dom'
import routes, { routeObj } from 'router'
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)

const RecursionRoute = (props: {
    routes: Array<routeObj>
    parentPath?: string
}) => {
    const { routes, parentPath = '' } = props
    return routes.map((item) => {
        const path = `${parentPath}${item.path}`
        return (
            <Route
                key={path}
                path={path}
                element={
                    <Suspense fallback={<div>loading...</div>}>
                        <item.component />
                    </Suspense>
                }
            >
                {item.children?.length &&
                    [
                        <Route
                            path={item.fullpath}
                            key={item.children.length}
                            element={
                                <Navigate
                                    to={item.children[0].fullpath || '/'}
                                />
                            }
                        />,
                    ].concat(
                        RecursionRoute({
                            routes: item.children,
                            parentPath: path,
                        })
                    )}
            </Route>
        )
    })
}

root.render(
    <React.StrictMode>
        <Router>
            <Routes>
                <Route path='/' element={<Navigate to={routes[0].path} />} />
                {RecursionRoute({ routes })}
                <Route path='*' element={<div>404 NOT FOUND</div>}></Route>
            </Routes>
        </Router>
    </React.StrictMode>
)
reportWebVitals()
